<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :label-position="labelPosition"
           :class="isEdit?'':'formItem'">
    <el-card class="box-card" shadow="never" style="margin-bottom: 0">

      <div slot="header" class="header-card">
        <span class="header-card-title">处置结果</span>
      </div>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="初期残值(元):" prop="initialResidualValue">
            <el-input :value="handleThousand(ruleForm.initialResidualValue)" v-if="isEdit" disabled/>
            <span v-else>{{ format_thousand(ruleForm.initialResidualValue) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="最新残值(元):" prop="latestResidualValue">
            <el-input :value="handleThousand(ruleForm.latestResidualValue)" v-if="isEdit" disabled/>
            <span v-else>{{ format_thousand(ruleForm.latestResidualValue) }}</span>
          </el-form-item>
        </el-col>


      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="承销商:" prop="underwriterType">
            <el-cascader v-if="isEdit" style="width: 100%" @change="handleSelect"
                         v-model="ruleForm.underwriterType"
                         :options="options" :props="propsObj" placeholder="请选择承销商" clearable/>
            <span v-else>{{ ruleForm.underwriterName }}</span>
<!--            <el-input v-model="ruleForm.underwriterName" @focus="handleFocus" ref="refInput" clearable-->
<!--                      placeholder="请选择承销商"/>-->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="成交价(元):" prop="finalPrice">
            <el-input v-model="ruleForm.finalPrice" v-if="isEdit" v-thousand @change="handleChange"
                      placeholder="请输入成交价"/>
            <span v-else>{{ format_thousand(ruleForm.finalPrice) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="差额(元):" prop="priceDifference"
                        :class="Number(ruleForm.priceDifference) > 0  ? 'greenColor'
                        : Number(ruleForm.priceDifference) ===0 ? '' :'redColor' "
          >
            <el-input v-if="isEdit" :value="handleThousand(ruleForm.priceDifference)"
                      disabled placeholder="成交价-初期残值"/>
            <span v-else :class="Number(ruleForm.priceDifference) > 0  ? 'greenSpan'
                        : Number(ruleForm.priceDifference) ===0 ? '' :'redSpan' ">
              {{ format_thousand(ruleForm.priceDifference) }}
            </span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="说明:" prop="routineRemark">
            <el-input v-if="isEdit" type="textarea" v-model="ruleForm.routineRemark" placeholder="请输入说明"
                      :rows="4" maxlength="500" show-word-limit/>
            <p v-else>{{ ruleForm.routineRemark }}</p>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件:" prop="routineAttachmentOss">
            <image-common v-model="ruleForm.routineAttachmentOss" :limit="20" :disabled="!isEdit" :upType="2"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>
  </el-form>
</template>

<script>
import {getSupplierList} from "@/api/vehicleDisposal/routineHandle.js"
import {toNumberSub} from "@/utils/utils"

export default {
  name: 'disposalResult',//处置结果
  dicts: ['supplier_business_type'],
  props: {
    value: {
      type: Object,
      default: () => {
      }
    },
    state: {
      type: String,
      default: "",
    },
  },
  computed: {
    ruleForm: {
      get() {
        let that = this;
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key);
          },
          set(target, key, value) {
            if (value) {
              that.handleClearValidate(key)
            }
            that.$emit("input", {...target, [key]: value});
            return true;
          },
        });
        return proxy;
      },
    },
    labelPosition() {
      if (this.state === 'write') {
        return 'top'
      } else {
        return 'right'
      }
    },
    isEdit() {
      let bool;
      switch (this.state) {
        case "write":
          bool = true;
          break;
        case "disabled":
          bool = false;
          break;
        case "readonly":
          bool = false;
          break;
      }
      return bool
    },
    handleThousand() {
      return function (val) {
        return this.format_thousand(val || 0)
      }
    }
  },
  watch: {},
  data() {
    return {
      rules: {
        underwriterType: [
          {required: true, message: '请选择承销商', trigger: 'blur'}
        ],
        finalPrice: [
          {required: true, message: '请输入成交价(元)', trigger: 'blur'}
        ]
      },
      options: [],
      propsObj: {
        checkStrictly: false,
        lazy: true,
        lazyLoad: this.handlePropsObj, //懒加载调用的方法
      },
      supplierListL: [],
      dictList: []

    };
  },
  created() {

  },
  mounted() {
  },
  methods: {
    handleFocus(){
      this.$SelectDialog({title: '', type: 'userNo'}).then(
          ({res, type}) => {
            this.value.underwriterId = res.customerId
            this.value.underwriterName = res.customerName
            if (this.value.underwriterName) {
              this.handleClearValidate('underwriterName')
            }
            this.$refs.refInput.blur()
          },
      );
    },

    handlePropsObj(node, resolve) {
      const {data, level, parent} = node;
      if (level === 0) {
        this._getDicts('supplier_business_type').then(res => {
          this.dictList = res
          const nodes = Array.from(res, item => ({
            value: item.dictValue,
            label: item.dictLabel,
            leaf: false
          }))
          resolve(nodes)
        })
      } else if (level === 1) {
        getSupplierList({supplierTypeCode: data.value}).then(res => {
          if (res.code === 200) {
            this.supplierListL = res.data || []
            const nodes = Array.from(this.supplierListL, item => ({
              value: item.supplierId,
              label: item.supplierName,
              leaf: true
            }))
            resolve(nodes)
          }
        })
      }
    },

    handleSelect(val) {
      this.ruleForm.underwriterType = this.value.underwriterType = val
      let a = this.supplierListL.map(item => {
        if (item.supplierId === val[1]) {
          return item.supplierName
        }
      }).filter(a => a)[0]
      this.value.underwriterId = this.ruleForm.underwriterId = val[1]
      this.value.underwriterName = this.ruleForm.underwriterName = a
      if (this.value.underwriterType) {
        this.handleClearValidate('underwriterName')
      }
    },

    handleChange(str) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      if (!msg.test(str)) {
        this.ruleForm.finalPrice = this.value.finalPrice = "";
      } else {
        this.ruleForm.finalPrice = this.value.finalPrice = str
            .toString()
            .match(/^\d+(?:\.\d{0,2})?/)[0];
      }
      this.ruleForm.priceDifference = toNumberSub(Number(this.ruleForm.finalPrice), Number(this.ruleForm.latestResidualValue))
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            resolve();
          } else {
            this.locateToErr()
            reject();
          }
        });
      });
    },

    locateToErr() {
      this.$nextTick(() => {
        let isError = document.getElementsByClassName('is-error')
        isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: 'center',
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: 'smooth',
        })
      })
    },

    //取消表单效验
    handleClearValidate(str) {
      this.$refs.ruleForm.clearValidate(str);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/cwgd/formScss.scss";

::v-deep .greenColor .el-form-item__label {
  color: green !important;
}

::v-deep .greenColor .el-form-item__content .is-disabled .el-input__inner {
  color: green !important;
}

::v-deep .redColor .el-form-item__label {
  color: red !important;
}

::v-deep .redColor .el-form-item__content .is-disabled .el-input__inner {
  color: red !important;
}

.greenSpan {
  color: green !important;
}

.redSpan {
  color: red !important;
}

</style>


